//Requires Model,View and App to be loaded first
//Put Event-handlers and control-flow related stuff here

var gxMenuMemonaut = null;
var gxMenuSettings = null;
var gxMenuBookmarks = null;
var gxMenuClip = null;
var gxMenuScrap = null;
var gxMenuNotebookList = null;
var gxMenuCommentList = null;
var gxMenuAttachIcon = null;

function Controller_init()
{
    initMenuMemonaut();
    initShortcuts();
}

scrapMenuItems = [
    { name: 'Attach Icon',  callback: insertIcon, tip:'CTRL+SHIFT+I' },
    { name: 'Info',  callback: toggleScrapInfo, tip:'CTRL+2' },
    { name: 'Bookmark',  callback: addBookmark, tip:'CTRL+3'},
    { name: 'Tweet This',  callback: addToTwitter, tip:'CTRL+SHIFT+T' },
    { name: 'Select Peers',  callback:  Note_selectPeers },
   {separator:true},
    { name: 'Color', callback: colorNote, tip:'CTRL+Q'},
    { name: 'Size',  callback: cycleSize, tip:'CTRL+E' },
    { name: 'Strikethrough',  callback: toggleStrikethrough, tip:'CTRL+K' },
    { name: 'Bold',  callback: toggleBold, tip:'CTRL+R' },
    { name: 'Italic',  callback: toggleItalic, tip:'CTRL+J' },
    { name: 'Underline',  callback: toggleUnderline, tip:'CTRL+U' },
    {separator:true},
    { name: 'Add Note Into',callback: addNoteInto, tip:'INSERT' },
    { name: 'Add Note As Next',  callback: addNoteNext, tip:'CTRL+ENTER' },
    { name: 'Edit',  callback: editScrap, tip:'F2' }
];

clipMenuItems =[
    { name: 'Shift Up', tip:'SHIFT+UP', callback: shiftUpScrap },
    { name: 'Shift Down', tip:'SHIFT+DOWN', callback: shiftDownScrap},
    { name: 'Shift Into Next', tip:'TAB or SHIFT+RIGHT', callback: shiftIntoNextScrap},
    { name: 'Shift Out', tip:'SHIFT+TAB', callback: shiftOutScrap},
    { separator: true},
    { name: 'Clone Content', callback: cloneNote, tip:'CTRL+SHIFT+C'},
    { name: 'Merge Into Previous', tip:'CTRL+SHIFT+UP', callback: mergePreviousScrap},
    { name: 'Merge Into Next', tip:'CTRL+SHIFT+DOWN', callback: mergeNextScrap},
    { name: 'Merge Into Parent', tip:'CTRL+SHIFT+LEFT',  callback: mergeParentScrap },
    { name: 'Split Lines', tip:'CTRL+SHIFT+RIGHT',  callback: splitScrapLines },
    { separator: true},
    { name: 'Cut', tip:'CTRL+X or SHIFT+DELETE',  callback:  cutScrap },
    { name: 'Paste', tip:'CTRL+V or SHIFT+INSERT',  callback:   pasteScrap},
    { name: 'Cancel Cut/Copy', tip:'ESCAPE',  callback:  cancelClipboard },
    { name: 'Delete', tip:'CTRL+DELETE',  callback: deleteScrap}
];

commentListMenuItems = [
    { name: 'Export',  callback:  CurrentScrap_export },
    { name: 'Shuffle List', callback: CommentList_shuffle, tip:'SHIFT+SPACE'},
    { name: 'Numbering On/Off',  callback:  CommentList_numberingToggle, tip:'CTRL+SPACE' },
    { name: 'Lock/Unlock',  callback:  CommentList_toggleLock, tip:'CTRL+SPACE' },
    {separator:true},
    { name: 'Numbering - 1,2,3',  callback:  CommentList_numberingDecimal },
    { name: 'Numbering - i,ii,iii', callback: CommentList_numberingLowerRoman},
    { name: 'Numbering - I,II,III', callback: CommentList_numberingUpperRoman},
    { name: 'Numbering - a,b,c',  callback:   CommentList_numberingLowerAlpha },
    { name: 'Numbering - A,B,C',  callback:   CommentList_numberingUpperAlpha },
    {separator:true},
    { name: 'Hide Peer Lists',  callback:  CommentList_hideLevel },
    { name: 'Show Peer Lists',  callback:  CommentList_showLevel },
    { name: 'Number Peer Lists',  callback:  CurrentScrap_formatPeers, tip:'CTRL+SHIFT+F'},
    {separator:true},
    { name: 'Select Notes',  callback:  CommentList_select},
    { name: 'Detach Notes',  callback:  CommentList_detach},
    { name: 'Delete Notes',  callback:   CommentList_delete }
];

attachIconMenuItems = [
    { name: 'Move Left', callback: AttachIcon_moveLeft},
    { name: 'Move Right', callback: AttachIcon_moveRight},
    { name: 'Change To Next', callback: AttachIcon_cycleNext, tip:'CTRL+I'},
    { name: 'Change To Previous', callback: AttachIcon_cyclePrevious, tip:'ALT+I'},
    { name: 'Remove',  callback: AttachIcon_remove, tip:'CTRL+SHIFT+DELETE'}
];

memonautMenuItems = [
    { name: 'Fold All', callback: AllNotes_fold},
    { name: 'Expand All', callback: AllNotes_expand},
    { name: 'Lock All', callback: AllNotes_lock},
    { name: 'Unlock All', callback: AllNotes_unlock},
    { name: 'Show Hidden', callback: AllNotes_show}
];

settingsMenuItems = [
    { name: 'Numbering On/Off', callback: Numbering_toggle},
    { name: 'Icons Show/Hide', callback: Icons_toggle},
    { name: 'Info Show/Hide', callback: NoteInfo_toggle},
    {separator:true},
    { name: 'Quick Actions Bar',  callback: toggleQuickActions}
];

bookmarkMenuItems = [
    { name: 'Rename',  callback:  Bookmark_rename },
    { name: 'Move Up',  callback:  Bookmark_moveUp },
    { name: 'Move Down', callback: Bookmark_moveDown},
    { name: 'Delete',  callback:   Bookmark_delete }
];

notebookListMenuItems = [
    { name: 'Move Up',  callback:  Notebook_moveUp },
    { name: 'Move Down', callback: Notebook_moveDown},
    { name: 'Remove From List',  callback:   Notebook_remove }
];

function initShortcuts()
{
shortcut.add("Ctrl+Up",CurrentScrap_movePrevious,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Down",CurrentScrap_moveNext,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Left",CurrentScrap_moveUp,
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Right",CurrentScrap_moveDown,
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Alt+Left",CurrentScrap_moveOut,
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Alt+Right",CurrentScrap_moveIn,
{'propagate':false,'type':'keydown','target':document});

shortcut.add("Insert",CurrentScrap_addNote,
{disable_in_input: true, 'type':'keydown','propagate':false,'target':document});

shortcut.add("Shift+Right",CurrentScrap_shiftIntoNext,
{disable_in_input: true,'type':'keydown','propagate':false,'target':document});
shortcut.add("Shift+Left",CurrentScrap_shiftIntoPrevious,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Tab",CurrentScrap_shiftIntoPrevious,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Shift+Tab",CurrentScrap_shiftOut,
{disable_in_input: true,'type':'keydown','propagate':false,'target':document});
shortcut.add("Shift+Up",CurrentScrap_shiftUp,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Shift+Down",CurrentScrap_shiftDown,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Shift+Up",CurrentScrap_mergePrevious,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Shift+Down",CurrentScrap_mergeNext,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Shift+Left",CurrentScrap_mergeParent,
{disable_in_input: true,'type':'keydown','propagate':false,'target':document});
shortcut.add("Ctrl+Shift+Right",CurrentScrap_split,
{disable_in_input: true,'type':'keydown','propagate':false,'target':document});

shortcut.add("F2",CurrentScrap_edit,
{'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+0",toggleHelp,
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+9",CurrentScrap_info,
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+8",CurrentScrap_bookmark,
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+7",Notepod_setFocus,
{'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+1", function (){setAddMode("eCurrentScrapAfter")},
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+2",function (){setAddMode("eCurrentScrapInto")},
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+3",function (){setAddMode("eCurrentScrapEdit")},
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+4",function (){setAddMode("eScrapbookTop")},
{'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+5",function (){setAddMode("eScrapbookLast")},
{'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+S",saveFile,
{'propagate':false,'type':'keydown','target':document});

shortcut.add("Escape", cancelClipboard,
{disable_in_input: true,'propagate':true,'type':'keydown','target':document});


shortcut.add("Shift+Delete",CurrentScrap_cut,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Shift+Insert",CurrentScrap_paste,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});

shortcut.add("Escape",escapeMode,
{disable_in_input: true,'propagate':false,'type':'keypress','target':document});

shortcut.add("Ctrl+Shift+C",CurrentScrap_clone,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Space",CurrentScrap_numbering,
{disable_in_input: false,'propagate':false,'type':'keypress','target':document});
shortcut.add("Shift+Space",CurrentScrap_shuffleParent,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});

shortcut.add("Shift+Home",CurrentScrap_scrollTo,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Shift+PageDown", CurrentScrap_fold,
{disable_in_input: true, 'type':'keydown','propagate':false,'target':document});

shortcut.add("Ctrl+I",CurrentScrap_cycleIcon,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Alt+I",CurrentScrap_cycleIconPrevious,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Shift+I",CurrentScrap_addIcon,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Shift+Delete",CurrentScrap_removeIcon,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Q",CurrentScrap_color,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+E",CurrentScrap_size,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+K",CurrentScrap_strikethrough,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+U",CurrentScrap_underline,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+J",CurrentScrap_italic,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+R",CurrentScrap_bold,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Shift+T",CurrentScrap_tweet,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Shift+Space",CurrentScrap_togglePeers,
    {disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Shift+F",CurrentScrap_formatPeers,
    {disable_in_input: false,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Delete",CurrentScrap_delete,
{disable_in_input: true,'propagate':false,'type':'keydown','target':document});
shortcut.add("Ctrl+Insert", Scrap_restore,
{disable_in_input: false,'propagate':false,'type':'keydown','target':document});

shortcut.add("Ctrl+Enter",CurrentScrap_addNext,
{disable_in_input: true,'type':'keydown','propagate':false,'target':document});

}

function initMenuMemonaut()
{
    gxMenuMemonaut = new Proto.Menu({
        selector: '#menuMemonaut',
        className: 'protomenu firefox',
        menuItems: memonautMenuItems,
        activator: 'click'
    });

    gxMenuSettings = new Proto.Menu({
        selector: '#menuSettings',
        className: 'protomenu firefox',
        menuItems: settingsMenuItems,
        activator: 'click'
    });

    gxMenuBookmarks = new Proto.Menu({
        selector: '#listBookmarks .iconBookmark',
        className: 'protomenu firefox',
        menuItems:  bookmarkMenuItems,
        activator: 'click'
    });

    gxMenuScrap = new Proto.Menu({
        selector: '#Scrapbook .iconActions',
        className: 'protomenu firefox',
        menuItems:  scrapMenuItems,
        beforeShow:setCurrentScrap,
        activator: 'click'
    });

    gxMenuClip = new Proto.Menu({
        selector: '#Scrapbook .iconClip',
        className: 'protomenu firefox',
        menuItems:  clipMenuItems,
        beforeShow:setCurrentScrap,
        activator: 'click'
    });

    gxMenuNotebookList = new Proto.Menu({
        selector: '#listNotebooks .iconNotebook',
        className: 'protomenu firefox',
        menuItems:  notebookListMenuItems,
        activator: 'click'
    });

    gxMenuCommentList = new Proto.Menu({
        selector: '#Scrapbook .foldindicator',
        className: 'protomenu firefox',
        menuItems:  commentListMenuItems,
        beforeShow: setAndExpandCurrentScrap,
        showOnLeftSide:true,
        activator: 'click'
    });

    gxMenuAttachIcon = new Proto.Menu({
        selector: '#Notebook .attachicon',
        className: 'protomenu firefox',
        menuItems:  attachIconMenuItems,
        beforeShow: setAndExpandCurrentScrap,
        activator: 'click'
    });
}

function shiftUpScrap(evt)
{
    var elmt = evt.target;
    Scrap_move(elmt, true);
}

function shiftDownScrap(evt)
{
    var elmt = evt.target;
    Scrap_move(elmt, false);
}

function deleteScrap(evt){
    Scrap_delete(evt.target);
}

function addBookmark(evt)
{
    Scrap_bookmark(evt.target);
}

function ScrapContent_onClick(ev){
    var target = ev.target.up('.wrapper').down('.scrap');
    CurrentScrap_setNew(target,true);
}

function ScrapIcon_onDoubleClick(ev){
    var target = ev.target.up('.wrapper').down('.scrap');
    $$('.protomenu').each(function(elmt){elmt.hide()});
    Scrap_toggleFold(target);
    CurrentScrap_setNew(target,true);
    ev.stop();
}

function FoldIndicator_onClick(ev){
    var target = ev.target.up(0).down('.scrap');
    Scrap_toggleFold(target);
    CurrentScrap_setNew(target,true);
}

function Notebook_moveUp(evt)
{
    var elmt = evt.target.up(0);
    Notebook_move(elmt, true);
}

function Notebook_moveDown(evt)
{
    var elmt = evt.target.up(0);
    Notebook_move(elmt, false);
}

function mergeParentScrap(evt)
{
    Scrap_mergeParent(evt.target);
}

function Notebook_remove(evt)
{
    var target = evt.target;
    target = target.up(0);
    target.remove();
    NotebookList_refresh();
}

function mergePreviousScrap(evt)
{
    var elmt = evt.target;
    Scrap_merge(elmt, true);
}

function mergeNextScrap(evt)
{
    var elmt = evt.target;
    Scrap_merge(elmt, false);
}

function toggleScrapInfo(evt)
{
    Scrap_info(evt.target);
}

function Bookmark_scrollTo(evt)
{
    var target = evt.target;

    var location = target.readAttribute('href');
    location=$(location.replace(/#/,''));
    if(location)
            CurrentScrap_setNew(location,true);
}

function shiftOutScrap(evt)
{
    var target = evt.target;
    Scrap_shiftOut(target);
}

function shiftIntoPreviousScrap(evt)
{
    var target = evt.target;
    Scrap_shiftIntoPrevious(target);
}

function shiftIntoNextScrap(evt)
{
    var target = evt.target;
    Scrap_shiftIntoNext(target);
}

function addNoteInto(evt)
{
    Scrap_addNote(evt.target, false);
    evt.stop();
}

function Bookmark_delete(evt)
{
    var target = evt.target;
    target = target.up(0);
    target.remove();
}

function Bookmark_rename(evt)
{
    var target = evt.target.up(0).down('.bookmark');
    target.edit();

}

function Bookmark_moveUp(evt)
{
    var elmt = evt.target.up(0);
    Bookmark_move(elmt, true);
}

function Bookmark_moveDown(evt)
{
    var elmt = evt.target.up(0);
    Bookmark_move(elmt, false);
}

function NotePod_handlerKeyDown(evt)
{
    if(evt.keyCode == Event.KEY_RETURN){
        if(evt.shiftKey) 
            return true;

        addScrap($('textareaScrap'));
        $('textareaScrap').value = '';
        NotePod_refresh();
        evt.stop();
    }
}

function NotePod_handlerKeyUp(evt)
{
    NotePod_updateLength();
}

function NotePod_refresh(){
    if(gbAddMode=="eCurrentScrapEdit"){
            if(!gxCurrentScrap) return;
            var text = gxCurrentScrap.down('.content').innerHTML;
            text = text.replace(/<br>/ig,'\n');
            $('textareaScrap').value = text;
    }
    NotePod_updateLength();
}

function NotePod_updateLength()
{
    var length = $('textareaScrap').value.length
    $('NotePodLength').innerHTML = length<10 ? "0" + length: length;
}

function editScrap(evt)
{
    Scrap_edit(evt.target);
}

function copyScrap(evt)
{
    Scrap_copy(evt.target);
}

function cutScrap(evt)
{
    Scrap_cut(evt.target);
}

function cancelClipboard(evt)
{
    if(gxClipboard){
        gxClipboard.removeClassName('clipboard');
    }
    gxClipboard = null;

    Selection_clear();
}

function ScrapIcon_onMouseDown(evt)
{
    var target = evt.target.up('.wrapper');
    gxDragger = target;
    var scrap = target.down('.scrap');
    CurrentScrap_setNew(scrap,true);

    if(evt.ctrlKey){
        Selection_toggle(target);
    }
    else{
        if(!Selection_contains(target))
            Selection_clear();
    }
}

function Drag_getSource(evt)
{
    var source=null;
    if(!gxDragger)
        return null;
    if(gaxSelection) {
        source = gaxSelection;
    }
    else{
        source = gxDragger;
    }
    gxDragger = null;
    return source;
}

function Content_onDrop(evt)
{
    var target = evt.target.up('.wrapper');
    if(!target)
        return;
    
    var source = Drag_getSource();
    if(!source) return;

    Scrap_moveAbsolute(source, target);
    displayStatus('Moved note.');
}

function ScrapIcon_onDrop(evt)
{
    var target = evt.target.up('.wrapper');
    if(!target)
        return;
    
    var source = Drag_getSource();
    if(!source) return;

    Scrap_moveAbsolute(source, target, true);
    displayStatus('Inserted note.');
}

function ScrapIcon_onMouseUp(evt)
{
    gxDragger = null;
}

function Notepod_setFocus(evt)
{
    $('textareaScrap').innerHTML = gxCurrentScrap? Scrap_getContent(gxCurrentScrap.up('.wrapper')): $('textareaScrap').innerHTML;
    $('textareaScrap').addClassName('editing');
    $('textareaScrap').focus();
}

function exportNote(evt)
{
    var target = evt.target.up('.wrapper');
    if(target) Note_export(target);
}

function pasteScrap(evt)
{
    Scrap_paste(evt.target);
}

function CurrentScrap_mergePrevious()
{
    if(!gxCurrentScrap) return;
    Scrap_merge(gxCurrentScrap, true);
}

function CurrentScrap_mergeNext(){
    if(!gxCurrentScrap) return;
    Scrap_merge(gxCurrentScrap, false);
}
function CurrentScrap_mergeParent(){
    if(!gxCurrentScrap) return;
    Scrap_mergeParent(gxCurrentScrap);
}

function CurrentScrap_addNote(){
    if(!gxCurrentScrap) return;
    Scrap_addNote(gxCurrentScrap,false);
}

function CurrentScrap_addNext(){
    if(!gxCurrentScrap) return;
    Scrap_addNote(gxCurrentScrap,true);
}

function CurrentScrap_delete(){
    if(!gxCurrentScrap) return;
    Scrap_delete(gxCurrentScrap, true);
}

function CurrentScrap_movePrevious(){
    if(!gxCurrentScrap) return;
    if(CurrentScrap_moveUp(true)){
        if(CurrentScrap_moveIn(true)){
            var check = gxCurrentScrap.up('.wrapper');
            while(check.next('.wrapper')){
                check = check.next('.wrapper');
            }
            CurrentScrap_setNew(check.down('.scrap'), true);
        }
    }
    else{
        CurrentScrap_moveOut(true);
    }
}

function CurrentScrap_moveNext(){
    if(!gxCurrentScrap) return;
    var check = gxCurrentScrap.up('.wrapper');
    if(!CurrentScrap_moveIn(true))
        if(!CurrentScrap_moveDown(true)){
            while(check){
                if(check.next('.wrapper')){
                    CurrentScrap_setNew(check.next('.wrapper').down('.scrap'), true);
                    return;
                }
                check = check.up('.wrapper');
            }
        }
}

function CurrentScrap_moveUp(bNoStatus){
    if(!gxCurrentScrap) return false;
    var check = gxCurrentScrap.up('.wrapper').previous('.wrapper');
    if(check){
        CurrentScrap_setNew(check.down('.scrap'),true);
        return true;
    }
    if(!bNoStatus) displayStatus("Cannot move up further at this level");
    return false;
}

function CurrentScrap_moveDown(bNoStatus){
    if(!gxCurrentScrap) return false;
    var check = gxCurrentScrap.up('.wrapper').next('.wrapper');
    if(check) {
        CurrentScrap_setNew(check.down('.scrap'),true);
        return true;
    }
    if(!bNoStatus) displayStatus("Cannot move down further at this level");
    return false;
 }

function CurrentScrap_moveIn(bNoStatus){
    if(!gxCurrentScrap) return false;
    var check = gxCurrentScrap.down('.commentlist');
    if (check){
        if(!check.visible()) {
            if(!check.hasClassName('locked'))
                expandNote(gxCurrentScrap);
            else{
                displayStatus('Moving over locked note.');
                return false;
            }
        }
        check = check.down('.wrapper');
        if(check){
            CurrentScrap_setNew(check.down('.scrap'),true);
            return true;
        }
    }
    if(!bNoStatus) displayStatus('Already at innermost note.');
    return false;
}

function CurrentScrap_moveOut(bNoStatus){
    if(!gxCurrentScrap) return false;
    var check = gxCurrentScrap.up('.commentlist');
    if (check){
        check = check.up('.wrapper');
        if(check){
            CurrentScrap_setNew(check.down('.scrap'), true);
            return true;
        }
    }
    if(!bNoStatus) displayStatus('Already at top level.');
    return false;
}

function CurrentScrap_shiftUp(){
    if(!gxCurrentScrap) return;
    Scrap_move(gxCurrentScrap, true);
}

function CurrentScrap_shiftDown(){
   if(!gxCurrentScrap) return;
   Scrap_move(gxCurrentScrap, false);
}

function CurrentScrap_shiftIntoPrevious(){
    if(!gxCurrentScrap) return;
    Scrap_shiftIntoPrevious(gxCurrentScrap);
}

function CurrentScrap_shiftIntoNext(){
    if(!gxCurrentScrap) return;
    Scrap_shiftIntoNext(gxCurrentScrap);
}

function CurrentScrap_shiftOut(){
    if(!gxCurrentScrap) return;
    Scrap_shiftOut(gxCurrentScrap);
}

function CurrentScrap_fold(){
    if(!gxCurrentScrap) return;
    Scrap_toggleFold(gxCurrentScrap);
}

function CurrentScrap_export(){
    if(!gxCurrentScrap) return;
    Note_export(gxCurrentScrap.up('.wrapper'));
}

function Icons_toggle()
{
    if(gbHideIcons){
        Icons_show();
    }
    else{
        Icons_hide();
    }
}

function Icons_show(){
    $$('#Notebook .clicker').each(function (elmt)	{
                    elmt.show();
            });

    $$('#Notebook .foldindicator').each(function (elmt)	{
                    elmt.show();
            });
    gbHideIcons = false;
}

function Icons_hide(){
    $$('#Notebook .clicker').each(function (elmt){
                    elmt.hide();});
    $$('#Notebook .foldindicator').each(function (elmt){
                    elmt.hide(); });
    gbHideIcons = true;
}

function NoteInfo_toggle()
{
    if(gbInfoDisplay){
        NoteInfo_hide();
    }
    else{
        NoteInfo_show();
    }
}

function NoteInfo_show(){
        $$('#Notebook .info').each(function (elmt){elmt.show()});
        gbInfoDisplay = true;
}
function NoteInfo_hide(){
	$$('#Notebook .info').each(function (elmt){elmt.hide()});
        gbInfoDisplay = false;
   
}
function Numbering_toggle()
{
    if(gbNumbering){
        $$('#Notebook ol').each(function (elmt){
            Numbering_off(elmt);
        });
        gbNumbering = false;
    }
    else{
        $$('#Notebook ol').each(function (elmt){
            Numbering_on(elmt);
        });
        gbNumbering = true;
    }
}

function Numbering_on(list){
    list.addClassName('numbering');
    if(list.hasClassName('decimal')) return;
    if(list.hasClassName('loweralpha')) return;
    if(list.hasClassName('upperalpha')) return;
    if(list.hasClassName('lowerroman')) return;
    if(list.hasClassName('upperroman')) return;
    list.addClassName('decimal');
}

function Numbering_off(list){
    list.removeClassName('numbering');
}

function cloneNote(evt){
    var target = evt.target;
    Scrap_clone(target);
}

function CurrentScrap_clone(){
    if(!gxCurrentScrap) return;
    Scrap_clone(gxCurrentScrap);
}

function AllNotes_fold(){
    $$('#Notebook .commentlist').each(function (elmt){
        if(!elmt.down('.current'))
            foldNote(elmt.up('.scrap'));
    });
}

function AllNotes_expand(){
    //TODO: Weird bug for IE. Content removed! Letting it be for 0.70
    if(Prototype.Browser.IE){
        displayStatus('Memonaut 0.70 - Limitation for IE');
        return;
    }

    $$('#Notebook .minimized').each(function (elmt){
            expandNote(elmt);
    });
 }

function AllNotes_lock(){
    $$('#Notebook .commentlist').each(function (elmt){
        if(elmt.up('.wrapper').visible())
            elmt.addClassName('locked');
    });
}

function AllNotes_unlock(){
    $$('#Notebook .commentlist').each(function (elmt){
        elmt.removeClassName('locked');
    });
}

function setAndExpandCurrentScrap(evt)
{
    setCurrentScrap(evt);
    var commentList = gxCurrentScrap.up('.wrapper').down('.commentlist');
    if(commentList){
        if(!commentList.hasClassName('locked'))
            expandNote(gxCurrentScrap);
    }
}

function CommentList_delete(evt){
    var target = evt.target.up('.wrapper');
    if(!confirm("Delete all notes under this section?")){
        return;
    }

    removeCommentList(target);
}

function CommentList_detach(evt){
    var target = evt.target.up('.wrapper');
    if(!confirm("Detach all notes from this section?")){
        return;
    }

    detachCommentList(target);
}

function CommentList_select(evt){
    var target = evt.target.up('.wrapper');
    selectCommentList(target);
}

function CommentList_toggleLock(evt){
    var target = evt.target.up('.wrapper');
    var list = target.down('.commentlist');

    if(list)
        lockToggleCommentList(list);
}

function CommentList_numberingToggle(evt){
    var target = evt.target.up('.wrapper');
    var list = target.down('.commentlist');
    if(list.hasClassName('numbering'))
        Numbering_off(list);
    else
        Numbering_on(list);
}

function CommentList_setNumberingStyle(wrapper, style){
    var list = wrapper.down('.commentlist');
    if(!list) return;
    if(!style) style = "decimal";

    list.removeClassName('decimal');
    list.removeClassName('loweralpha');
    list.removeClassName('upperalpha');
    list.removeClassName('lowerroman');
    list.removeClassName('upperroman');

    if(style!="none"){
        list.addClassName('numbering');
        list.addClassName(style);
    }
}

function CommentList_numberingDecimal(evt){
    var target = evt.target.up('.wrapper');
    CommentList_setNumberingStyle(target,'decimal');
}

function CommentList_numberingLowerAlpha(evt){
    var target = evt.target.up('.wrapper');
    CommentList_setNumberingStyle(target,'loweralpha');
}

function CommentList_numberingUpperAlpha(evt){
    var target = evt.target.up('.wrapper');
    CommentList_setNumberingStyle(target,'upperalpha');
}

function CommentList_numberingLowerRoman(evt){
    var target = evt.target.up('.wrapper');
    CommentList_setNumberingStyle(target,'lowerroman');
}

function CommentList_numberingUpperRoman(evt){
    var target = evt.target.up('.wrapper');
    CommentList_setNumberingStyle(target,'upperroman');
}

function Numbering_cycle(wrapper){
    var list = wrapper.up('ol');

    if(!list.hasClassName('numbering')){
        Numbering_on(list);
        return;
    }

    if(list.hasClassName('decimal'))
        {list.removeClassName('decimal');       list.addClassName('loweralpha');    return;}
    if(list.hasClassName('loweralpha'))
        {list.removeClassName('loweralpha');    list.addClassName('upperalpha');    return;}
    if(list.hasClassName('upperalpha'))
        {list.removeClassName('upperalpha');    list.addClassName('lowerroman');    return;}
    if(list.hasClassName('lowerroman'))
        {list.removeClassName('lowerroman');    list.addClassName('upperroman');    return;}
    if(list.hasClassName('upperroman'))
        {list.removeClassName('upperroman');    list.removeClassName('numbering');    return;}


}

function CurrentScrap_numbering(){
    if(!gxCurrentScrap) return;
    Numbering_cycle(gxCurrentScrap.up('.wrapper'));
}

function CommentList_cycleNumbering(evt){
    Numbering_cycle(evt.target.up('.wrapper').down('.wrapper'));
    stopEvent(evt);
}

function escapeMode()
{
    $$('.protomenu').each(function(elmt){elmt.hide()});
    $('Notebook').focus();

}

function CommentList_shuffle(evt)
{
    var wrapper = evt.target.up('.wrapper');
    var list = wrapper.down('.commentlist');
    if(!list) return;
    Notes_shuffle(list);
}

function CurrentScrap_shuffle(){
    if(!gxCurrentScrap) return;
    var wrapper = gxCurrentScrap.up('.wrapper');
    var list = wrapper.down('.commentlist');
    if(!list) return;
    Notes_shuffle(list);
}

function CurrentScrap_shuffleParent(){
    if(!gxCurrentScrap) return;
    var list = gxCurrentScrap.up('ol');
    if(!list) return;
    var restore = gxCurrentScrap;
    CurrentScrap_reset();
    Notes_shuffle(list);
    CurrentScrap_setNew(restore, true)
}

function CurrentScrap_scrollTo()
{
    if(!gxCurrentScrap) return;
    gxCurrentScrap.focus();
    gxCurrentScrap.scrollTo();
}

function addNoteNext(evt){
    Scrap_addNote(evt.target, true);
}

function toggleQuickActions(){
    gbQuickActions = !gbQuickActions;
    CurrentScrap_setNew(gxCurrentScrap,true)
}

function AllNotes_show(){
    $$('#Notebook .wrapper').each(function (elmt){
        if(!elmt.visible())
            elmt.show();
    });
}

function insertIcon(evt){
    Scrap_addIcon(evt.target);
}

function activateIcon(img){
    img.setAttribute('title', 'Click for menu, right-click to change.');
    img.addClassName('attachicon');
    img.observe('contextmenu', cycleIcon)
}

function cycleIcon(evt){
    var target = evt.target;
    if(!evt.shiftKey) Scrap_cycleIcon(target);
    else Scrap_cycleIcon(target, true);
    stopEvent(evt);
}

function stopEvent(evt){
    evt.cancelBubble = true;
    evt.returnValue = false;

    //e.stopPropagation works in Firefox.
    if (evt.stopPropagation) {
            evt.stopPropagation();
            evt.preventDefault();
    }
}

function CurrentScrap_cycleIcon(){
    if(!gxCurrentScrap) return;
    var lastIcon = Scrap_getLastIcon(gxCurrentScrap);
    if(lastIcon)
        Scrap_cycleIcon(lastIcon);
    else
        Scrap_addIcon(gxCurrentScrap);
}

function CurrentScrap_cycleIconPrevious(){
    if(!gxCurrentScrap) return;
    var lastIcon = Scrap_getLastIcon(gxCurrentScrap);
    if(lastIcon)
        Scrap_cycleIcon(lastIcon,true);
}

function CurrentScrap_removeIcon(){
    if(!gxCurrentScrap) return;
    var lastIcon = Scrap_getLastIcon(gxCurrentScrap);
    if(lastIcon)
        Scrap_removeIcon(lastIcon);
}

function CurrentScrap_addIcon(){
    if(!gxCurrentScrap) return;
    Scrap_addIcon(gxCurrentScrap);

}

function AttachIcon_cycleNext(evt){
    Scrap_cycleIcon(evt.target);
}

function AttachIcon_cyclePrevious(evt){
    Scrap_cycleIcon(evt.target, true);
}

function AttachIcon_remove(evt){
    Scrap_removeIcon(evt.target);
}

function AttachIcon_moveLeft(evt){
    var icon = evt.target;
    var swapper = icon.previous('.attachicon');
    if(swapper){
        AttachIcon_swap(icon, swapper);
    }
}

function AttachIcon_moveRight(evt){
    var icon = evt.target;
    var swapper = icon.next('.attachicon');
    if(swapper){
        AttachIcon_swap(icon, swapper);
    }
}

function Content_toggleStrikethrough(wrapper){
    var content = wrapper.down('.content');
    if(!content.hasClassName('strikethrough')) content.addClassName('strikethrough');
    else content.removeClassName('strikethrough');
}

function toggleStrikethrough(evt){
    var target = evt.target.up('.wrapper');
    Content_toggleStrikethrough(target);
}

function CurrentScrap_strikethrough(){
    if(!gxCurrentScrap) return
     Content_toggleStrikethrough(gxCurrentScrap.up('.wrapper'));
}

function Content_toggleUnderline(wrapper){
    var content = wrapper.down('.content');
    if(!content.hasClassName('underline')) content.addClassName('underline');
    else content.removeClassName('underline');
}

function toggleUnderline(evt){
    var target = evt.target.up('.wrapper');
    Content_toggleUnderline(target);
}

function CurrentScrap_underline(){
    if(!gxCurrentScrap) return
     Content_toggleUnderline(gxCurrentScrap.up('.wrapper'));
}

function Content_toggleItalic(wrapper){
    var content = wrapper.down('.content');
    if(!content.hasClassName('italic')) content.addClassName('italic');
    else content.removeClassName('italic');
}

function toggleItalic(evt){
    var target = evt.target.up('.wrapper');
    Content_toggleItalic(target);
}

function CurrentScrap_italic(){
    if(!gxCurrentScrap) return
     Content_toggleItalic(gxCurrentScrap.up('.wrapper'));
}

function Content_toggleBold(wrapper){
    var content = wrapper.down('.content');
    if(!content.hasClassName('bold')) content.addClassName('bold');
    else content.removeClassName('bold');
}

function toggleBold(evt){
    var target = evt.target.up('.wrapper');
    Content_toggleBold(target);
}

function CurrentScrap_bold(){
    if(!gxCurrentScrap) return
     Content_toggleBold(gxCurrentScrap.up('.wrapper'));
}

function Content_cycleSize(wrapper){
    var content = wrapper.down('.content');

    if(content.hasClassName('large'))
        {content.removeClassName('large');      content.addClassName('xlarge');    return;}
    if(content.hasClassName('xlarge'))
        {content.removeClassName('xlarge');     content.addClassName('xxlarge');    return;}
    if(content.hasClassName('xxlarge'))
        {content.removeClassName('xxlarge');    content.addClassName('xxsmall');    return;}
    if(content.hasClassName('xxsmall'))
        {content.removeClassName('xxsmall');    content.addClassName('xsmall');    return;}
    if(content.hasClassName('xsmall'))
        {content.removeClassName('xsmall');    return;}

    content.addClassName('large');
}

function cycleSize(evt){
    var target = evt.target.up('.wrapper');
    Content_cycleSize(target);
}

function CurrentScrap_size(){
    if(!gxCurrentScrap) return
     Content_cycleSize(gxCurrentScrap.up('.wrapper'));
}

function addToTwitter(evt){
    var target = evt.target.up('.wrapper');
    Scrap_tweet(target);
}

function CurrentScrap_tweet(){
    if(!gxCurrentScrap) return;
    Scrap_tweet(gxCurrentScrap.up('.wrapper'));
}

function colorNote(evt){
    var target = evt.target.up('.wrapper');
    Scrap_color(target);
}

function CurrentScrap_color(){
    if(!gxCurrentScrap) return;
    Scrap_color(gxCurrentScrap.up('.wrapper'));
}

function CommentList_showHideLevel(evt, bShow){
    var target = evt.target.up('.wrapper');
    var selector = 'ol ol';
    var looper = target.up('.wrapper');

    while(looper){
        selector += ' ol';
        looper = looper.up('.wrapper');
    }

    var siblings = $('Notebook').getElementsBySelector(selector);
    for(var i=0;i<siblings.length;i++){
        if(bShow)
            siblings[i].show();
        else
            siblings[i].hide();
    }
}

function Note_selectPeers(evt){
    Selection_clear();
    var target = evt.target.up('.wrapper');
    var selector = 'ol';
    var looper = target.up('.wrapper');

    while(looper){
        selector += ' ol';
        looper = looper.up('.wrapper');
    }

    var siblings = $('Notebook').getElementsBySelector(selector);
    for(var i=0;i<siblings.length;i++){
        siblings[i].immediateDescendants().each(function (elmt)
                { 
                Selection_toggle(elmt);
                });
    }
}

function CommentList_showLevel(evt){
    CommentList_showHideLevel(evt,true);
}

function CommentList_hideLevel(evt){
    CommentList_showHideLevel(evt,false);
}

function Scrap_split(wrapper){
    var text = Scrap_getContent(wrapper, true);
    var content = wrapper.down('.content');
    var lines = text.split(/<br>/i);
    if(lines.length<=1) {displayStatus('No lines to split.'); return;}
    
    var commentList = Scrap_getCommentList(wrapper);

    for(var i=0;i<lines.length;i++){
        var note = Scrap_createWithWrapper(lines[i]);
        commentList.insert({bottom:note});
        Scrap_activateWrapper(note);
    }

    content.innerHTML = 'Split Note';
    
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();
    displayStatus('Split note content.');
}

function splitScrapLines(evt){
    Scrap_split(evt.target.up('.wrapper'));
}

function CurrentScrap_togglePeers(){
    if(!gxCurrentScrap) return;

    var list = gxCurrentScrap.down('.commentlist');
    if(!list) return;

    var bShow = true;
    if(list.visible())
        bShow=false;

    var target = gxCurrentScrap;
    var selector = 'ol';
    var looper = target.up('.wrapper');

    while(looper){
        selector += ' ol';
        looper = looper.up('.wrapper');
    }

    var siblings = $('Notebook').getElementsBySelector(selector);
    for(var i=0;i<siblings.length;i++){
        if(bShow)
            siblings[i].show();
        else
            siblings[i].hide();
    }
    intelliScroll(target);
}

function CurrentScrap_formatPeers(){
    if(!gxCurrentScrap) return;

    var list = gxCurrentScrap.down('.commentlist');
    if(!list) {
        list = gxCurrentScrap.up('ol');
        if(!list)
            return;
    }

    var style = 'none';
    if(list.hasClassName('decimal')) style='decimal';
    if(list.hasClassName('loweralpha')) style='loweralpha';
    if(list.hasClassName('upperalpha')) style='upperalpha';
    if(list.hasClassName('lowerroman')) style='lowerroman';
    if(list.hasClassName('upperroman')) style='upperroman';

    var target = gxCurrentScrap;
    var selector = 'ol';
    var looper = target.up('.wrapper');

    while(looper){
        selector += ' ol';
        looper = looper.up('.wrapper');
    }

    var siblings = $('Notebook').getElementsBySelector(selector);
    for(var i=0;i<siblings.length;i++){
        CommentList_setNumberingStyle(siblings[i].up('.wrapper'),style)
    }
    intelliScroll(target);
}

function adder_addNote(evt){
    Scrap_addNote(evt.target, true, true);
    evt.stop();
}

function CurrentScrap_split(){
    if(!gxCurrentScrap) return;
    Scrap_split(gxCurrentScrap.up('.wrapper'));
}

function ScrapIcon_onRightClick(evt){
    if(evt.shiftKey){
        Scrap_pasteFormatting(evt.target.up('.wrapper'));
    }
    else{
        Scrap_copyFormatting(evt.target.up('.wrapper'));
    }
    evt.stop();
}

function endAdder_addNote(evt){
    evt.stop();
    Scrap_addFreeNote(true);
}

function setAddMode(eMode){
    var elmt = $('dropdownAddMode');
    var selectIndex = -1;
    switch(eMode){
        case "eCurrentScrapAfter": selectIndex=0; break;
        case "eCurrentScrapInto": selectIndex=1; break;
        case "eCurrentScrapEdit": selectIndex=2; break;
        case "eScrapbookTop": selectIndex=3; break;
        case "eScrapbookLast": selectIndex=4; break;
        default: eMode="eScrapbookTop"; selectIndex=3; break;
    }
    elmt.selectedIndex = selectIndex;
}